﻿using System;
using Puerts;
using UnityEngine;
#if NodeCanvas
using NodeCanvas.Framework;
using ParadoxNotion.Design;

namespace Puerts
{
    public delegate void PuertsActionInit(PuertsActionTask task);
    [Category("✫ Puerts")]
    [Description("设置一个puerts函数执行")]
    public class PuertsActionTask : ActionTask<GraphOwner>,IDisposable
    {
        [RequiredField]
        public BBParameter<TypeScript> module;

        public System.Action _OnInit;
        public System.Action<float> _OnUpdate;
        public System.Action _OnStop;
        public System.Action _OnExecute;
    
        protected override string OnInit()
        {
            try
            {
                JsEnv env = JsManager.Instance.GetJsEnv();
                var init = env.Eval<PuertsActionInit>($"require('{module.value.module}').init;");
                init?.Invoke(this);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            _OnInit?.Invoke();
            return base.OnInit();
        }

        protected override void OnExecute()
        {
            _OnExecute?.Invoke();
        }

        protected override void OnUpdate()
        {
            _OnUpdate?.Invoke(elapsedTime);
        }

        protected override void OnStop()
        {
            _OnStop?.Invoke();
        }

        public void Dispose()
        {
            _OnInit = null;
            _OnStop = null;
            _OnUpdate = null;
            _OnExecute = null;
        }
    }
}
#endif